#include "aerial\Object\Panel.h"
#include "aerial\Scene\Event.h"

#include "aerial\Scene\SceneManager.h"

using namespace air;

Panel::Panel(hgeResourceManager* _hgeResMan, float x, float y, float w, float h)
	: IGuiObject(hgeResMan), callback(0)
{
	width = w;
	height = h;
	status = 0;

	flashw = 0.0f;
	frame = new hgeSprite(0, 0, 0, w, h);
	flash = new hgeSprite(0, 0, 0, 0, h);

	frame->SetHotSpot(0.0f, 0.0f);
	flash->SetHotSpot(0.0f, 0.0f);

	frame->SetColor(0x1f0000ff);
	flash->SetColor(0x2fffffff);
	ox = x;
	oy = y;
	rect.Set(x, y, x + w, y + h);
}

Panel::~Panel()
{
	delete callback;
	delete frame;
	delete flash;
}

void Panel::SetTransfromationTween(float _dx, float _dy, float dt, Event* _evnt)
{
	dx = _dx;
	dy = _dy;
	time = dt;
	status = 1;
	
	vx = ( dx - ox ) / dt;
	vy = ( dy - oy ) / dt;
	if (callback) delete callback;
	callback = _evnt;
}


void Panel::Update(float dt)
{
	if (status)
	{
		moveTo( ox + vx * dt, oy + vy * dt );
		time -= dt;
		if (time < 0) {
			status = 0;
			moveTo(dx, dy);
			if (callback) 
			{
				callback->callback();
				delete callback;
				callback = 0;
			}
		}
	}
	flashw += frame->GetWidth() * dt;
	if (flashw > width) flashw = 0;
	isPositionUpdate = true;
}

void Panel::Render()
{
	calcAbsolutePosition();
	frame->Render(rect.x1, rect.y1);
	flash->RenderStretch(rect.x1, rect.y1, rect.x1 + flashw, rect.y1 + height);
}

void Panel::placeGuiObjectProportional(IGuiObject* iGuiObj, float px, float py)
{
	iGuiObj->setRelativeLayout();
	iGuiObj->setLayoutOffset(px, py);
	container.append(iGuiObj);
}

void Panel::placeGuiObjectOffset(IGuiObject* iGuiObj, float x, float y)
{
	iGuiObj->setAbsoluteLayout();
	iGuiObj->setLayoutOffset(x, y);
	container.append(iGuiObj);
}

bool Panel::addToGui(SceneManager* sceneMan, IGuiObject* _anchor)
{
	anchor = _anchor;
	sceneMan->addGuiObject(this);
	Node<IGuiObject*>* p = container.Head()->next;
	Node<IGuiObject*>* t = container.Tail();
	while (p != t)
	{
		p->val->addToGui(sceneMan, this);
		p = p->next;
	}
	return true;
}


